// 压缩图片
const compressImage = (file, maxWidth = 200, maxHeight = 200) => {
  return new Promise((resolve, reject) => {
    // 创建一个 FileReader 对象
    const reader = new FileReader();
    // 读取文件
    reader.readAsDataURL(file);
    // 文件读取完成后触发
    reader.onload = function (event) {
      // 创建一个 Image 对象
      const img = new Image();
      // 图片加载完成后触发
      img.onload = function () {
        // 创建一个 Canvas 对象
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        // 计算压缩后的尺寸
        let width = img.width;
        let height = img.height;
        if (width > maxWidth) {
          height *= maxWidth / width;
          width = maxWidth;
        }
        if (height > maxHeight) {
          width *= maxHeight / height;
          height = maxHeight;
        }
        // 设置 Canvas 尺寸
        canvas.width = width;
        canvas.height = height;
        // 绘制图片到 Canvas
        ctx.drawImage(img, 0, 0, width, height);
        // 将 Canvas 转为 Base64 字符串
        const compressedDataUrl = canvas.toDataURL(file.type);
        // 将 Base64 字符串转为 Blob 对象
        const compressedFile = dataURLtoBlob(compressedDataUrl);
        // 返回压缩后的图片文件
        resolve(compressedFile);
      };
      // 设置 Image 的 src
      img.src = event.target.result;
    };
    // 文件读取失败后触发
    reader.onerror = function (event) {
      reject(event.target.error);
    };
  });
};

// 将 Base64 字符串转为 Blob 对象
function dataURLtoBlob(dataURL) {
  const parts = dataURL.split(",");
  const contentType = parts[0].split(":")[1];
  const byteString = atob(parts[1]);
  const arrayBuffer = new ArrayBuffer(byteString.length);
  const uint8Array = new Uint8Array(arrayBuffer);
  for (let i = 0; i < byteString.length; i++) {
    uint8Array[i] = byteString.charCodeAt(i);
  }
  return new Blob([arrayBuffer], { type: contentType });
}

export default compressImage;
